package com.aiapphub.SystemCode.controller;

import com.aiapphub.BaseCode.common.ResponseResult;
import com.aiapphub.SystemCode.entity.AppMapping;
import com.aiapphub.SystemCode.service.AppMappingService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * App映射控制器
 */
@RestController
@RequestMapping("/api/app/mapping")
public class AppMappingController {

    @Autowired
    private AppMappingService appMappingService;

    /**
     * 获取所有配置列表（管理端使用）
     */
    @GetMapping("/list")
    public ResponseResult list() {
        List<AppMapping> mappings = appMappingService.listAllMappings();
        Map<String, Object> data = new HashMap<>();
        data.put("data", mappings);
        return ResponseResult.okResult(data);
    }

    /**
     * 获取所有启用的配置列表（前端使用）
     */
    @GetMapping("/user/list")
    public ResponseResult userList() {
        List<AppMapping> mappings = appMappingService.listEnabledMappings();
        Map<String, Object> data = new HashMap<>();
        data.put("data", mappings);
        return ResponseResult.okResult(data);
    }

    /**
     * 根据API Key获取配置详情
     */
    @GetMapping("/info/{realApiKey}")
    public ResponseResult info(@PathVariable("realApiKey") String realApiKey) {
        AppMapping mapping = appMappingService.getMappingByApiKey(realApiKey);
        Map<String, Object> data = new HashMap<>();
        data.put("data", mapping);
        return ResponseResult.okResult(data);
    }

    /**
     * 保存配置
     */
    @PostMapping("/save")
    public ResponseResult save(@RequestBody AppMapping mapping) {
        // 检查App名称是否已存在
        QueryWrapper<AppMapping> wrapper = new QueryWrapper<>();
        wrapper.eq("app_name", mapping.getAppName());
        AppMapping existing = appMappingService.getOne(wrapper);
        if (existing != null) {
            return ResponseResult.errorResult(500, "App名称已存在");
        }
        
        boolean result = appMappingService.saveMapping(mapping);
        return result ? ResponseResult.okResult() : ResponseResult.errorResult(500, "保存失败");
    }

    /**
     * 更新配置
     */
    @PostMapping("/update")
    public ResponseResult update(@RequestBody AppMapping mapping) {
        // 检查App名称是否已存在（排除当前记录）
        QueryWrapper<AppMapping> wrapper = new QueryWrapper<>();
        wrapper.eq("app_name", mapping.getAppName())
                .ne("real_api_key", mapping.getRealApiKey());
        AppMapping existing = appMappingService.getOne(wrapper);
        if (existing != null) {
            return ResponseResult.errorResult(500, "App名称已存在");
        }
        
        boolean result = appMappingService.updateMapping(mapping);
        return result ? ResponseResult.okResult() : ResponseResult.errorResult(500, "更新失败");
    }

    /**
     * 删除配置
     */
    @PostMapping("/delete/{realApiKey}")
    public ResponseResult delete(@PathVariable("realApiKey") String realApiKey) {
        boolean result = appMappingService.deleteMapping(realApiKey);
        return result ? ResponseResult.okResult() : ResponseResult.errorResult(500, "删除失败");
    }

    /**
     * 启用/禁用配置
     */
    @PostMapping("/status")
    public ResponseResult updateStatus(@RequestParam("realApiKey") String realApiKey, @RequestParam("status") Integer status) {
        boolean result = appMappingService.updateStatus(realApiKey, status);
        return result ? ResponseResult.okResult() : ResponseResult.errorResult(500, "更新状态失败");
    }
}
